package com.book.utils.utils;
import com.alipay.api.java_websocket.util.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
 * base64编码解码工具
 * @author Sean
 *
 */
public class Base64Util {

	

	public static byte[] decryptBASE64(String key) throws Exception {
		return (new BASE64Decoder()).decodeBuffer(key);
	}


	public static String encryptBASE64(byte[] key) throws Exception {
		return (new BASE64Encoder()).encodeBuffer(key);
	}

	public static String convertFileToBase64(String imgPath) {
		byte[] data = null;
		// 读取图片字节数组
		try {
			InputStream in = new FileInputStream(imgPath);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 对字节数组进行Base64编码，得到Base64编码的字符串
		BASE64Encoder encoder = new BASE64Encoder();
		String base64Str = encoder.encode(data);
		return base64Str;
	}

	/**
	 * 将base64字符串，生成文件
	 */
	public static File convertBase64ToFile(String fileBase64String, String filePath, String fileName) {

		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		File file = null;
		try {
			File dir = new File(filePath);
			if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
				dir.mkdirs();
			}

			BASE64Decoder decoder = new BASE64Decoder();
			byte[] bfile = decoder.decodeBuffer(fileBase64String);

			file = new File(filePath + File.separator + fileName);
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(bfile);
			return file;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}
	public static String getImageStr(File file, String fileType) throws IOException {
		String fileContentBase64 = null;
		String base64Str = "data:" + fileType + ";base64,";
		String content = null;
		//将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		InputStream in = null;
		byte[] data = null;
		//读取图片字节数组
		try {
			in = new FileInputStream(file);
			data = new byte[in.available()];
			in.read(data);
			in.close();
			//对字节数组Base64编码
			if (data == null || data.length == 0) {
				return null;
			}
			content = Base64.encodeBytes(data);
			if (content == null || "".equals(content)) {
				return null;
			}
			fileContentBase64 = base64Str + content;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				in.close();
			}
		}
		return fileContentBase64;
	}
	
}
